<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Use correct character set. -->
  <meta charset="utf-8">
  <!-- Tell IE to use the latest, best version. -->
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <!-- Make the application on mobile take up the full browser screen and disable user scaling. -->
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
  <title>Hello World!</title>
  <script src="Cesium/Cesium.js"></script>
  <style>
      @import url(Cesium/Widgets/widgets.css);
      html, body, #cesiumContainer {
          width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden;
      }
  </style>
</head>
<body>
  <div id="cesiumContainer"></div>
  <div style="position:absolute;top: 0;display:none;">
	<canvas id="canvas"></canvas>
  </div>
<script src="../dist/wind-gl.js"></script>
  <script>
    var viewer = new Cesium.Viewer('cesiumContainer',{
		useDefaultRenderLoop: false
	});
	
	var canvas = document.getElementById('canvas'); // eslint-disable-line

	const pxRatio = Math.max(Math.floor(window.devicePixelRatio) || 1, 2);
	canvas.width = canvas.clientWidth;
	canvas.height = canvas.clientHeight;

	const gl = canvas.getContext('webgl', {antialiasing: false});

	const wind = window.wind = new WindGL(gl);
	wind.numParticles = 65536;
	
	worldRectangle = viewer.scene.primitives.add(new Cesium.Primitive({
        geometryInstances : new Cesium.GeometryInstance({
            geometry : new Cesium.RectangleGeometry({
                rectangle : Cesium.Rectangle.fromDegrees(-180.0, -90.0, 180.0, 90.0),
                vertexFormat : Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT
            })
        }),
        appearance : new Cesium.EllipsoidSurfaceAppearance({
            aboveGround : false
        }),
        show : true
    }));
	
	applyDiffuseMaterial(worldRectangle,canvas);
	function frame() {
		if (wind.windData) {
			wind.draw();
			viewer.render();
			//applyDiffuseMaterial(worldRectangle);
		}
		requestAnimationFrame(frame);
	}
	frame();

	function timer(){
		updateRect(worldRectangle,canvas);
		console.log('update');
		setTimeout(function(){timer()},1000);
	}
	timer();
	
	
	const windFiles = {
		0: '2016112000',
		6: '2016112006',
		12: '2016112012',
		18: '2016112018',
		24: '2016112100',
		30: '2016112106',
		36: '2016112112',
		42: '2016112118',
		48: '2016112200'
	};
	const meta = {
		'2016-11-20+h': 0,
		'retina resolution': true,
		'github.com/mapbox/webgl-wind': function () {
			window.location = 'https://github.com/mapbox/webgl-wind';
		}
	};
	
	updateWind(0);
	updateRetina();
	console.log(canvas);

	function updateRetina() {
		const ratio = meta['retina resolution'] ? pxRatio : 1;
		canvas.width = 540*ratio;//canvas.clientWidth * ratio;
		canvas.height = 360*ratio;//canvas.clientHeight * ratio;
		wind.resize();
	}
	
	function updateWind(name) {
		getJSON('wind/' + windFiles[name] + '.json', function (windData) {
			const windImage = new Image();
			windData.image = windImage;
			windImage.src = 'wind/' + windFiles[name] + '.png';
			windImage.onload = function () {
				wind.setWind(windData);
			};
		});
	}
	
	function getJSON(url, callback) {
		const xhr = new XMLHttpRequest();
		xhr.responseType = 'json';
		xhr.open('get', url, true);
		xhr.onload = function () {
			if (xhr.status >= 200 && xhr.status < 300) {
				callback(xhr.response);
			} else {
				throw new Error(xhr.statusText);
			}
		};
		xhr.send();
	}

	function applyDiffuseMaterial(primitive,canvas) {
		/*primitive.appearance.material =  new Cesium.ImageMaterialProperty({
			image:new Cesium.CallbackProperty(function() {
				return canvas;
			}, false),
			transparent:true
		});*/
		var img = convertCanvasToImage(canvas);
		primitive.appearance.material = new Cesium.Material({
			fabric : {
				type : 'Image',
				uniforms : {
					image : img.src
				}
			}
		});
	}

	function updateRect(primitive,canvas){
		var img = convertCanvasToImage(canvas);
		primitive.appearance.material.uniforms.image=img.src;
	}

	function convertCanvasToImage(canvas) {
		var image = new Image();
		image.src = canvas.toDataURL("image/png");
		return image;
  }
  </script>
</body>
</html>
